package cn.bs.io;


import org.junit.Test;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;

/**
 * Created by ROC on 2014-10-14.
 */
public class ZipCompress {
    static final int BUFFER = 8192;
    /**
     * zip多文件压缩
     * @param files
     */
      public void compress(String[] files,String destFile){
          try {
              FileOutputStream f = new FileOutputStream(destFile);
              //输出校验流,采用Adler32更快
              //CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32())
              CheckedOutputStream cos = new CheckedOutputStream(f,new CRC32());
              ZipOutputStream zos = new ZipOutputStream(cos);
              //创建压缩输出流
              //BufferedOutputStream out = new BufferedOutputStream(zos);
              //设置Zip文件注释
              zos.setComment("A test of java Zipping");
             for(String file: files){
                 //针对单个文件建立读取流
                 File dest = new File(file);
                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(dest));
                 //BufferedReader bin = new BufferedReader(new FileReader(file));
                // ZipEntry ZIP 文件条目
                 //putNextEntry 写入新条目，并定位到新条目开始处
                 zos.putNextEntry(new ZipEntry(dest.getName()));
                 int count;
                 byte data[] = new byte[BUFFER];
                 while ((count = bis.read(data, 0, BUFFER)) != -1) {
                     zos.write(data, 0, count);

                 }
                 bis.close();
                // out.flush();
             }

              zos.close();
              //zos.flush();
              //zos.close();
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
          }


      }

    /***
     *解压缩文件
     * @param zip
     */
      public void uncompress(String zip){
          try {
              System.out.println("uncompress.............");
              ZipFile zipFile = new ZipFile(zip);
              Enumeration e = zipFile.entries();
              while(e.hasMoreElements()){
                 ZipEntry entry = (ZipEntry) e.nextElement();
                 String fileName =  entry.getName();
                  System.out.println("fileName======" + fileName);
              }
          } catch (IOException e) {
              e.printStackTrace();
          }

      }

    @Test
    public void testCompress() {
        compress(new String[]{"d:/aa/1.txt", "d:/aa/2.txt"}, "d:/test.zip");

    }

    @Test
    public void testUnCompress() {
        uncompress("d:/test.zip");

    }
}
